// ++++++++++++++++++++++++++++++++++++++++
// 《零基础Go语言算法实战》源码
// ++++++++++++++++++++++++++++++++++++++++
// Author:廖显东（ShirDon）
// Blog:https://www.shirdon.com/
// Gitee:https://gitee.com/shirdonl/goAlgorithms.git
// Buy link :https://item.jd.com/14101229.html
// ++++++++++++++++++++++++++++++++++++++++

package main

import "fmt"

const (
	mod = 1024
)

type HashMap struct {
	set [mod]*listNode
}

type listNode struct {
	key  int
	val  int
	next *listNode
}

// 初始化数据结构。
func Constructor() HashMap {
	arr := [mod]*listNode{}
	return HashMap{set: arr}
}

func (hm *HashMap) Put(key int, value int) {
	i := key % mod
	ptr := hm.set[i]
	for ptr != nil {
		if ptr.key == key {
			ptr.val = value
			return
		} else {
			ptr = ptr.next
		}
	}
	node := &listNode{key: key, val: value, next: hm.set[i]}
	hm.set[i] = node
}

// 返回指定键映射到的值，如果不包含键的映射，则返回 -1
func (hm *HashMap) Get(key int) int {
	ptr := hm.set[key%mod]
	for ptr != nil {
		if ptr.key == key {
			return ptr.val
		} else {
			ptr = ptr.next
		}
	}
	return -1
}

// 如果HashMap映射包含键的映射，则删除指定值键的映射
func (hm *HashMap) Remove(key int) {
	i := key % mod
	ptr := hm.set[i]
	prev := &listNode{next: ptr}
	head := prev
	for ptr != nil {
		if ptr.key == key {
			prev.next = ptr.next
			break
		} else {
			prev = prev.next
			ptr = ptr.next
		}
	}
	hm.set[i] = head.next
}

func main() {
	obj := Constructor()
	obj.Put(1, 1)
	obj.Put(2, 2)
	res1 := obj.Get(1)
	fmt.Println(res1)
	res2 := obj.Get(2)
	fmt.Println(res2)
	obj.Remove(2)
}

//$ go run interview3-9.go
//1
//2
